package com.dlee.mvc.aop;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

import com.dlee.mvc.container.BeanContainer;
import com.dlee.mvc.model.AspectMapping;

/**
 * jdk动态代理增强处理过程
 * @author d.lee
 * @date 2012-8-10
 */
public class JdkProxy implements InvocationHandler
{
    private Object target;
    private AspectMapping am;
    
    public JdkProxy (Object target,AspectMapping am)
    {
        this.am = am;
        this.target = target;
    }
    
    public Object createProxy(Class interfaceObject)
    {
        return Proxy.newProxyInstance (JdkProxy.class.getClassLoader (), new Class<?>[]{interfaceObject}, this);
    }
    
    @Override
    public Object invoke (Object proxy, Method method, Object[] args) throws Throwable
    {
        System.out.println ("-----jdk增强-----");
        Object result = null;  
        try {  
            //在指定的方法上进行处理
            if(null != am.getAopMethod () && am.getAopMethod ().equals (method.getName ()))
            {
                if(null != am.getBeforeMethod () )
                {
                    Object aspect = BeanContainer.getBean (am.getBeanId ());
                    Method m = aspect.getClass ().getDeclaredMethod (am.getBeforeMethod (), new Class[]{});
                    m.invoke (aspect, new Object[]{});
                }
                result = method.invoke(target, args);  
                if(null != am.getAfterMethod ())
                {
                    Object aspect = BeanContainer.getBean (am.getBeanId ());
                    Method m = aspect.getClass ().getDeclaredMethod (am.getAfterMethod (), new Class[]{});
                    result = m.invoke(aspect, new Object[]{}); 
                }
            }
            else
            {
                result = method.invoke(target, args); 
            }
        } catch (Exception e) {  
        }finally{  
        }  
        return result; 
    }
}
